// 多数元素

package Leetcode;

import java.util.HashMap;
import java.util.Map;

class Solution_169_1 {
    public int majorityElement(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i]) == false) {
                map.put(nums[i], 0);
            } else {
                map.put(nums[i], map.get(nums[i]) + 1);
            }
        }
        for (Integer k : map.keySet()) {
            if (map.get(k) > nums.length / 2)
                return k;
        }
        return 0;
    }
}

class Solution_169_2 {
    public int majorityElement(int[] nums) {
        int winner = nums[0]; //表示占领高地的士兵的阵营
        int count = 1; //表示高地同阵营的士兵数量
        for (int i = 1; i < nums.length; i++) {
            if (count == 0) {
                winner = nums[i];
                count = 1;
                continue;
            }
            // 如果士兵同一阵营
            if (winner == nums[i]) {
                count++;
            } else {
                count--;
            }
        }
        return winner;
    }
}